自定義元件的插槽
元件插槽的基本用法
- 首先,建立一個名為slot.html的檔案,在其中撰寫以下核心範例程式:
<body>
<div id="Application">
<my-container></my-container>
</div>
<script>
const App = Vue.createApp({
template: '<my-container></my-container>'
})
const containerComponent = {
template:'<div style="border-style:solid;border-color:red;border-width:10px"></div>'
}
App.component("my-container", containerComponent)
App.mount("#Application")
</script>
</body>
- 上面的程式中,定義了一個名為my-container的容器元件,這個容器本身非常簡單,只是新增了紅色的邊框。
- 如果想直接嘗試向容器元件內部新增子元素是不可行的,例如:
<my-container>元件內部</my-container>
- 執行程式,你會發現元件中並沒有任何文字被著色,要讓自定義元件支援插槽,需要使用slot標籤來指定插槽的位置。